<template>
	<!-- 注册修改主体 -->
	<a-modal
		:visible="visible"
		width="640px"
		class="add-invoicing-entity"
		:title="isDisable ? '编辑主体信息' : '添加主体信息'"
		centered
		destroyOnClose
		:maskClosable="false"
		@cancel="cancel">
		<a-form ref="formRef" :model="modelRef" :rules="modelRules" :style="{height: '75vh'}" layout="vertical">
			<div class="flex1 auto-y">
				<a-row :gutter="[16, 8]" v-if="modelRef.rejectionReason">
					<a-col :span="24">
						<div class="tip-info">
							<svg-icon icon-class="Warning-Circle-Fill" />
							{{ modelRef.rejectionReason }}
						</div>
					</a-col>
				</a-row>
				<a-row :gutter="[16, 8]">
					<a-col :span="24">
						<a-form-item label="是否在票通平台注册过企业：" htmlFor="label" name="sourceType" class="display-flex">
							<a-radio-group v-model:value="modelRef.sourceType" @change="resetForm" :disabled="isDisable">
								<a-radio :value="false">否</a-radio>
								<a-radio :value="true">是</a-radio>
							</a-radio-group>
						</a-form-item>
						<div v-if="modelRef.sourceType" class="warning-margin">
							<a-typography-text type="warning">
								<question-circle-outlined />
								注：请确保以下信息与在票通平台注册的数据一致，否则会影响开票
							</a-typography-text>
						</div>
					</a-col>
				</a-row>
				<template v-if="!modelRef.sourceType">
					<a-row :gutter="[16, 8]">
						<a-col :span="12">
							<a-form-item label="企业名称:" htmlFor="label" name="name">
								<a-auto-complete v-model:value="modelRef.name" v-bind="searchOption">
									<template #default="item">
										<a-input v-model:value="modelRef.name" :maxlength="40"  @input="handleInput" placeholder="请输入的企业名称" />
									</template>
									<template v-if="loadings.search" #notFoundContent>
										<a-spin spinning tip="正在搜索，请稍候……" />
									</template>
								</a-auto-complete>

								<!-- <a-select v-model:value="modelRef.name" v-bind="searchOption">
									<template v-if="loadings.search" #notFoundContent>
										<a-spin spinning tip="正在搜索，请稍候……" />
									</template>
									<template #dropdownRender="{menuNode: menu}">
										<v-nodes :vnodes="menu" />
										<a-divider style="margin: 4px 0" />
										<a-space style="padding: 4px 8px">
											<a-button type="text" @mousedown.prevent="addItem">
												<template #icon>
													<plus-outlined />
												</template>
												添加当前输入的企业名称
											</a-button>
										</a-space>
									</template>
								</a-select> -->
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="税号:" htmlFor="label" name="taxpayerNum">
								<a-input
									v-model:value="modelRef.taxpayerNum"
									@blur="modelRef.taxpayerNum = modelRef.taxpayerNum.trim()"
									:disabled="isDisable"
									placeholder="请输入税号" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="[16, 8]">
						<a-col :span="12">
							<a-form-item label="法人姓名:" htmlFor="label" name="legalPersonName">
								<a-input
									v-model:value="modelRef.legalPersonName"
									placeholder="请输入法人姓名"
									:minLength="2"
									:maxLength="50" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="联系人姓名:" htmlFor="label" name="contactsName">
								<a-input v-model:value="modelRef.contactsName" placeholder="请输入联系人姓名" :maxLength="16" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="[16, 8]">
						<a-col :span="12">
							<a-form-item label="联系人邮箱:" htmlFor="label" name="contactsEmail">
								<a-input v-model:value="modelRef.contactsEmail" placeholder="请输入联系人邮箱" :maxLength="50" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="联系人手机号:" htmlFor="label" name="contactsPhone">
								<a-input
									v-model:value="modelRef.contactsPhone"
									type="tel"
									placeholder="该号码将用户登录发票管理系统"
									:maxLength="11" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="[16, 8]">
						<a-col :span="12">
							<a-form-item label="市(地区)名称:" htmlFor="label" name="cityName">
								<a-input v-model:value="modelRef.cityName" placeholder="请输入市(地区)名称" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="地区编码:" htmlFor="label" name="regionCode">
								<a-input v-model:value="modelRef.regionCode" :maxlength="2" placeholder="请输入地区编码" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="[16, 8]">
						<a-col :span="12">
							<a-form-item label="详细地址:" htmlFor="label" name="enterpriseAddress">
								<a-input v-model:value="modelRef.enterpriseAddress" placeholder="请输入详细地址" maxLength="89" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="企业税控设备类型:" htmlFor="label" name="taxControlDeviceTypes">
								<a-select
									v-model:value="modelRef.taxControlDeviceTypes"
									max-tag-count="responsive"
									mode="multiple"
									style="width: 100%"
									:options="equipmentList"
									:field-names="{label: 'name', value: 'id'}"
									placeholder="请选择企业税控设备类型:"></a-select>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="[16, 8]">
						<a-col :span="12">
							<a-form-item label="营业执照图片:" htmlFor="label" name="taxRegistrationCertificateImageId">
								<file-upload v-model:file="subjectInfo.sealUrl" :limit="1" :multiple="false" :fileSize="2">
									<template #icon>
										<plus-outlined />
									</template>
									<template #tip>添加图片</template>
								</file-upload>
								<div>图片需小于2M</div>
							</a-form-item>
						</a-col>
					</a-row>
				</template>
				<template v-if="modelRef.sourceType">
					<a-row :gutter="[16, 8]">
						<a-col :span="12">
							<a-form-item label="企业名称:" htmlFor="label" name="name">
								<a-input v-model:value="modelRef.name" disabled placeholder="根据税号自动填充,请先输入税号" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="税号:" htmlFor="label" name="taxpayerNum">
								<a-input-search
									v-model:value="modelRef.taxpayerNum"
									placeholder="请输入已注册的企业税号"
									enter-button
									size="default"
									@search="getOrgInfoSpi" />
								<!-- <a-input v-model:value="modelRef.taxpayerNum" @blur="modelRef.taxpayerNum = modelRef.taxpayerNum.trim()" placeholder="请输入税号" /> -->
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :span="12">
						<a-col :span="12">
							<a-form-item label="企业税控设备类型:" htmlFor="label" name="taxControlDeviceTypes">
								<a-select
									v-model:value="modelRef.taxControlDeviceTypes"
									max-tag-count="responsive"
									mode="multiple"
									style="width: 100%"
									:options="equipmentList"
									:field-names="{label: 'name', value: 'id'}"
									placeholder="请选择企业税控设备类型："></a-select>
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter="[16, 8]" v-for="(item, index) in modelRef.machineInfos" :key="index">
						<a-col v-if="show()" :span="7">
							<a-form-item label="税盘号:" htmlFor="label" :rules="[{required: true, message: '请输入税盘号'}]">
								<a-input v-model:value="item.machineCode" placeholder="请输入税盘号" />
							</a-form-item>
						</a-col>
						<a-col v-if="show()" :span="7">
							<a-form-item label="终端号:" htmlFor="label" :rules="[{required: true, message: '请输入终端号'}]">
								<a-input v-model:value="item.extensionNum" placeholder="请输入终端号" />
							</a-form-item>
						</a-col>
						<a-col v-if="show()" :span="7">
							<a-form-item label="单张开票限额:" htmlFor="label" :rules="[{required: true, message: '请输入单张开票限额'}]">
								<a-input-number
									v-model:value="item.invoiceMaxValue"
									:min="0.01"
									:precision="2"
									placeholder="请输入单张开票限额" />
							</a-form-item>
						</a-col>
						<a-col v-if="show()" :span="1">
							<div class="circle">
								<plus-circle-outlined
									v-color="{color: 'primary'}"
									v-if="index === modelRef.machineInfos.length - 1"
									@click="machineInfosPush()" />
							</div>
						</a-col>
						<a-col :span="1">
							<div class="circle">
								<minus-circle-outlined v-color="{color: 'primary'}" v-if="index !== 0" @click="machineInfosReduce(index)" />
							</div>
						</a-col>
					</a-row>
				</template>
			</div>
		</a-form>
		<template #footer>
			<a-button type="primary" :loading="loading" :disabled="disabled" @click="sendRequest">提交</a-button>
		</template>
	</a-modal>
</template>
<script setup lang="ts">
	import {reactive, ref, watch, defineComponent} from 'vue'
	import {message} from 'ant-design-vue'
	import {QuestionCircleOutlined, PlusOutlined, PlusCircleOutlined, MinusCircleOutlined} from '@ant-design/icons-vue'
	import {certRules, sealUrlRules} from '@/rules/invoice-administration'
	import {orgInfoRegister, orgInfoSpi, getImgById, orgInfoId, saveOrUpdate, spiNameMatching} from '@/api/invoice-administration'
	import {equipmentList, reviewStatus} from '@/utils/invoice-administration'
	import FileUpload from '@/components/common/file-upload.vue'
	import XEUtils from 'xe-utils'

	const VNodes = defineComponent({
		props: {
			vnodes: {
				type: Object,
				required: true
			}
		},
		render() {
			return this.vnodes
		}
	})

	const addItem = e => {
		e.preventDefault()
		const hasOption = searchOption.options.some(e => e.name === searchOption.searchInput)
		if (searchOption.searchInput.length > 40) {
			message.warning('当前企业名称超过40字，无法添加')

			return
		}
		if (hasOption) {
			message.warning('当前已有企业名称，无法添加')

			return
		}
		searchOption.options.unshift({
			name: searchOption.searchInput,
			isShift: true,
			taxpayerNum: new Date().getTime()
		})
	}

	const modelRef = reactive<any>({
		id: null,
		cityName: null,
		contactsEmail: null,
		contactsName: null,
		contactsPhone: null,
		enterpriseAddress: null,
		sourceType: false,
		legalPersonName: null,
		name: null,
		regionCode: null,
		taxControlDeviceTypes: [],
		taxRegistrationCertificateImageId: null,
		taxpayerNum: null,
		machineInfos: [
			{
				extensionNum: null,
				machineCode: null,
				invoiceMaxValue: null
			}
		]
		// sealUrl:''
	})
	const subjectInfo = reactive<any>({
		attachment: false,
		sealUrl: null
	})
	const visibles = reactive<any>({
		sealUrl: null,
		subjectState: null,
		attachment: false
	})
	const modelRules = ref<any>([])
	const imgList = reactive([])

	const props = defineProps<{
		detail: object
		visible: boolean
	}>()
    const handleInput = () => {
      modelRef.name = modelRef.name.replace(/\s/g, '')
    }
	const isDisable = ref<boolean>(false)
	console.log(props)
	const formRules = {
		...certRules
	}
	const loading = ref<boolean>(false)
	const disabled = ref(false)
	// 重置表单
	const resetForm = () => {
		Object.keys(modelRef).forEach(key => {
			if (key !== 'sourceType' && key !== 'machineInfos') {
				modelRef[key] = null
			}
		})
		Object.keys(subjectInfo).forEach(key => {
			subjectInfo[key] = null
		})
		modelRef.taxControlDeviceTypes = []
		modelRef.machineInfos = [
			{
				extensionNum: null,
				machineCode: null,
				invoiceMaxValue: null
			}
		]
	}
	//提交
	const sendRequest = () => {
		formRef.value.validate().then(() => {
			if (!modelRef.id) {
				delete modelRef.id
			}
			if (modelRef.hasOwnProperty('sealUrl')) {
				delete modelRef.sealUrl
			}
			let parameter, requestInterface
			if (modelRef.sourceType) {
				requestInterface = saveOrUpdate
				parameter = {
					machineInfos: show() ? modelRef.machineInfos : [],
					name: modelRef.name,
					taxControlDeviceTypes: modelRef.taxControlDeviceTypes,
					taxpayerNum: modelRef.taxpayerNum,
					sourceType: modelRef.sourceType ? 2 : 1
				}
			} else {
				if (!modelRef.taxRegistrationCertificateImageId) {
					return message.error('请上传营业执照')
				}
				requestInterface = orgInfoRegister
				parameter = {
					cityName: modelRef.cityName,
					contactsEmail: modelRef.contactsEmail,
					contactsName: modelRef.contactsName,
					contactsPhone: modelRef.contactsPhone,
					enterpriseAddress: modelRef.enterpriseAddress,
					sourceType: modelRef.sourceType ? 2 : 1,
					legalPersonName: modelRef.legalPersonName,
					name: modelRef.name,
					regionCode: modelRef.regionCode,
					taxControlDeviceTypes: modelRef.taxControlDeviceTypes,
					taxRegistrationCertificateImageId: modelRef.taxRegistrationCertificateImageId,
					taxpayerNum: modelRef.taxpayerNum
				}
			}
			console.log(parameter, 'parameter')
			if (modelRef.id) {
				parameter.id = modelRef.id
			}
			loading.value = true
			requestInterface(parameter)
				.then(({data}) => {
					message.success('操作成功')
					emit('success')
					cancel()
				})
				.finally(() => (loading.value = false))
		})
	}
	//表单赋值
	const setForm = (data: any) => {
		Object.keys(data).forEach(key => {
			modelRef[key] = data[key]
		})
		modelRef.sourceType = data.sourceType === 1 ? false : true
		if (modelRef.taxControlDeviceTypes && modelRef.taxControlDeviceTypes.length) {
			let taxControlDeviceTypes = [...modelRef.taxControlDeviceTypes]
			modelRef.taxControlDeviceTypes = []
			for (let item of taxControlDeviceTypes) {
				modelRef.taxControlDeviceTypes.push(parseInt(item))
			}
		} else {
			modelRef.taxControlDeviceTypes = []
		}
	}
	//根据税号查询主体信息
	const getOrgInfoSpi = () => {
		orgInfoSpi(modelRef.taxpayerNum).then(ref => {
			// setForm(ref.data)
			modelRef.name = ref.data.name
			// subjectInfo.subjectState = ref.data.hasOwnProperty('reviewStatus') ? reviewStatus[parseInt(ref.data.reviewStatus)].name : ''
		})
	}
	//根据id查询企业信息
	const getOrgInfoId = () => {
		if (!props.detail.id) {
			return
		}
		orgInfoId(props.detail.id).then(ref => {
			setForm(ref.data)
			// subjectInfo.subjectState = ref.data.hasOwnProperty('reviewStatus') ? reviewStatus[parseInt(ref.data.reviewStatus)].name : ''
		})
	}
	// 发票抬头搜索
	const searchOption = reactive<any>({
		options: [],
		allowClear: true,
		showSearch: true,
		searchInput: '',
		maxlength: 10,
		optionFilterProp: 'name',
		// placeholder: '请输入输入企业名称',
		fieldNames: {label: 'name', value: 'taxpayerNum'},
		style: {
			width: '100%'
		},
		onSearch(like: string) {
			searchOption.searchInput = like
			if (searchOption.searchInput.length > 40) {
				message.warning('当前企业名称超过40字，无法添加')
				return
			}
			if (like.length >= 4 && like.trim()) {
				buyerNameSearch(like)
			}
		},
		onblur(e) {
			e.preventDefault()
			return false
		},
		onSelect(value: string) {
			searchOption.options.forEach(e => {
				if (e.taxpayerNum === value) {
					modelRef.name = e.name
					if (!e.isShift) {
						modelRef.taxpayerNum = e.taxpayerNum
						modelRef.enterpriseAddress = e.enterpriseAddress
					}
				}
			})
			// formRef.value?.clearValidate()
		},
		onDeselect() {
			modelRef.name = null
			modelRef.taxpayerNum = null
			modelRef.enterpriseAddress = null
		},
		getPopupContainer(triggerNode: HTMLDivElement) {
			return triggerNode ? triggerNode.parentNode : document.body
		}
	})

	const loadings = reactive({
		search: false,
		submit: false,
		detail: false
	})
	const buyerNameSearch = XEUtils.debounce((like: string) => {
		let params = {
			name: like
		}

		loadings.search = true
		spiNameMatching(params)
			.then((res: any) => {
				searchOption.options = res.data
			})
			.finally(() => (loadings.search = false))
	}, 300)

	//查图片
	const imgById = () => {
		getImgById(props.detail.id).then(res => {
			subjectInfo.sealUrl = res.data[0] || {}
			modelRef.taxRegistrationCertificateImageId = res.data[0]?.id || ''
		})
	}
	const formRef = ref()
	const getDisabled = (value: boolean) => {
		disabled.value = value
		modelRules.value = sealUrlRules
	}

	/**
	 * 图片上传回调
	 */
	const gitImg = () => {
		modelRef.taxRegistrationCertificateImageId = subjectInfo.sealUrl.bizId
		// subjectInfo.sealUrl = subjectInfo.sealUrl.url
		// formRef.value.validate()
		// modelRules.value = certRules
	}
	//税盘号+终端号数组修改
	const machineInfosPush = () => {
		modelRef.machineInfos.push({
			extensionNum: null,
			machineCode: null
		})
	}
	const machineInfosReduce = index => {
		modelRef.machineInfos.splice(index, 1)
	}

	const emit = defineEmits(['update:visible', 'success'])
	const cancel = () => {
		emit('update:visible', false)
		resetForm()
	}
	watch(
		() => props.visible,
		(newVal, oldVal) => {
			if (newVal) {
				isDisable.value = props.detail.hasOwnProperty('id') ? true : false
				if (isDisable.value) {
					getOrgInfoId()
					imgById()
				}
				// updateInfo()
				modelRules.value = certRules
			}
		}
	)
	watch(
		() => subjectInfo.sealUrl,
		newVal => {
			modelRef.taxRegistrationCertificateImageId = newVal?.id || ''
			formRef.value.validate()
			modelRules.value = certRules
		}
	)
	// watch([() => modelRef.sourceType, () => modelRef.taxpayerNum], (newVal, oldVal) => {
	// 	if (newVal[0]) {
	// 		resetForm()
	// 		// if (newVal[0] && newVal[1]) {

	// 		// }
	// 	}
	// })

	//是否展示
	const show = () => {
		if (modelRef.taxControlDeviceTypes?.includes(1) || modelRef.taxControlDeviceTypes?.includes(2)) {
			return true
		}
		return false
	}
</script>
<style lang="less">
	.add-invoicing-entity {
		.ant-modal-body {
			overflow-y: auto;
		}
		.url-input {
			position: absolute;
			width: 125px;
			height: 128px;
			z-index: -1;
			top: 0;
			left: 0;
		}
		.text {
			font-size: 12px;
			color: #999;
		}
		.ant-form-vertical .display-flex {
			flex-direction: initial;
			.ant-form-item-control-input-content {
				margin: -8px 0 0 10px;
			}
		}
		.tip-info {
			width: 100%;
			height: 40px;
			line-height: 40px;
			background: #fffbe6;
			border-radius: 2px 2px 2px 2px;
			opacity: 1;
			border: 1px solid #ffe58f;
			font-size: 14px;
			margin-bottom: 20px;
			padding-left: 16px;
		}
		.circle {
			width: 100%;
			margin-top: 35px;
			& > :last-child {
				margin-left: 10px;
			}
		}
		.warning-margin {
			margin-top: -25px;
			margin-bottom: 10px;
		}
	}
</style>
